import { StyleSheet, Text, View, Pressable, FlatList, PanResponder, Alert } from 'react-native';
import React, { useState, useCallback, useEffect } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import Modal from 'react-native-modal';
import { useTranslation } from 'react-i18next';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import LinearGradient from 'react-native-linear-gradient';
import dayjs from 'dayjs';
import { height, isIos, px2dp, scale, width } from '~/utils/px2dp';
import { appStore } from '~/store';

dayjs.locale(appStore.app.language == 'zh' ? 'zh-cn' : 'en'); // 设置全局语言为中文
interface Props {
    currentDate: any;
    visible: boolean;
    onToggleVisible: Function;
    onSelectDate: any;
}
export default function SelectCalendar(props: Props) {
    const { t } = useTranslation();
    const { visible, onToggleVisible, onSelectDate, currentDate } = props;
    const insets = useSafeAreaInsets();
    const weekDays = [
        t('SelectCalendar.t1'),
        t('SelectCalendar.t2'),
        t('SelectCalendar.t3'),
        t('SelectCalendar.t4'),
        t('SelectCalendar.t5'),
        t('SelectCalendar.t6'),
        t('SelectCalendar.t7'),
    ];
    const [selectedDate, setSelectedDate] = useState<dayjs.Dayjs | any>(
        props.currentDate ? dayjs(props.currentDate) : dayjs(),
    );
    const today = dayjs();
    const [currentMonth, setCurrentMonth] = useState(today.month());
    const [currentYear, setCurrentYear] = useState(today.year());
    const getDaysArray = useCallback((month, year) => {
        const firstDay = dayjs(new Date(year, month, 1));
        const lastDay = dayjs(new Date(year, month + 1, 0));
        const daysArray: any = [];
        let startDay = firstDay.day() === 0 ? 6 : firstDay.day() - 1;
        for (let i = 0; i < startDay; i++) {
            daysArray.push(null);
        }

        for (let day = 1; day <= lastDay.date(); day++) {
            daysArray.push(day);
        }
        return daysArray;
    }, []);
    const daysArray = getDaysArray(currentMonth, currentYear);
    const prevMonth = () => {
        let month = currentMonth - 1;
        let year = currentYear;
        if (month < 0) {
            month = 11;
            year -= 1;
        }
        setCurrentMonth(month);
        setCurrentYear(year);
        // 更新选中日期
        if (selectedDate) {
            const daysInNewMonth = dayjs(new Date(year, month + 1, 0)).date(); // 当月天数
            const newDay = Math.min(selectedDate.date(), daysInNewMonth); // 如果上次选的日子超过本月天数，就取本月最后一天
            const newDate = dayjs(new Date(year, month, newDay));
            setSelectedDate(newDate);
            props.onSelectDate?.(newDate.format('YYYY-MM-DD'));
        }
    };

    const nextMonth = () => {
        let month = currentMonth + 1;
        let year = currentYear;
        if (month > 11) {
            month = 0;
            year += 1;
        }
        // 限制不能超过当前月
        const today = dayjs();
        if (year > today.year() || (year === today.year() && month > today.month())) {
            Alert.alert(t('SelectCalendar.t8'), t('SelectCalendar.t9'));
            return;
        }
        setCurrentMonth(month);
        setCurrentYear(year);
        if (selectedDate) {
            const daysInNewMonth = dayjs(new Date(year, month + 1, 0)).date();
            const newDay = Math.min(selectedDate.date(), daysInNewMonth);
            const newDate = dayjs(new Date(year, month, newDay));
            setSelectedDate(newDate);
            props.onSelectDate?.(newDate.format('YYYY-MM-DD'));
        }
    };
    useEffect(() => {
        if (currentDate) {
            setSelectedDate(dayjs(currentDate));
        }
    }, [currentDate]);
    const panResponder = PanResponder.create({
        onMoveShouldSetPanResponder: (_, gestureState) => {
            return Math.abs(gestureState.dx) > 10;
        },
        onPanResponderRelease: (_, gestureState) => {
            if (gestureState.dx > 50) {
                handlePrevMonth();
            } else if (gestureState.dx < -50) {
                handleNextMonth();
            }
        },
    });
    const handlePrevMonth = () => {
        let newMonth = currentMonth - 1;
        let newYear = currentYear;
        if (newMonth < 0) {
            newMonth = 11;
            newYear -= 1;
        }

        setCurrentMonth(newMonth);
        setCurrentYear(newYear);

        // 更新选中日期
        if (selectedDate) {
            const daysInNewMonth = dayjs(new Date(newYear, newMonth + 1, 0)).date(); // 新月份天数
            const newDay = Math.min(selectedDate.date(), daysInNewMonth); // 避免溢出，比如从 31 号跳到 2 月
            const newDate = dayjs(new Date(newYear, newMonth, newDay));
            setSelectedDate(newDate);
            props.onSelectDate?.(newDate.format('YYYY-MM-DD'));
        }
    };

    const handleNextMonth = () => {
        const today = dayjs();
        if (currentYear > today.year() || (currentYear === today.year() && currentMonth >= today.month())) {
           Alert.alert(t('SelectCalendar.t8'), t('SelectCalendar.t9'));
            return;
        }
        let newMonth = currentMonth + 1;
        let newYear = currentYear;
        if (newMonth > 11) {
            newMonth = 0;
            newYear += 1;
        }
        setCurrentMonth(newMonth);
        setCurrentYear(newYear);
        if (selectedDate) {
            const daysInNewMonth = dayjs(new Date(newYear, newMonth + 1, 0)).date();
            const newDay = Math.min(selectedDate.date(), daysInNewMonth);
            const newDate = dayjs(new Date(newYear, newMonth, newDay));
            setSelectedDate(newDate);
            props.onSelectDate?.(newDate.format('YYYY-MM-DD'));
        }
    };
    const renderDay = (day, index) => {
        const dateObj: any = day ? dayjs(new Date(currentYear, currentMonth, day)) : null;
        const isToday = dateObj?.isSame(today, 'day');
        const isSelected = dateObj?.isSame(selectedDate, 'day');
        return (
            <View key={index} style={styles.dayContainer}>
                {day && (
                    <Pressable
                        onPress={() => {
                            setSelectedDate(dateObj);
                            onSelectDate && onSelectDate(dateObj.format('YYYY-MM-DD'));
                            onToggleVisible();
                        }}>
                        <View style={[styles.dayBox, (isToday || isSelected) && styles.todayBox]}>
                            <Text style={[styles.dayText, isToday && styles.todayText]}>{day}</Text>
                        </View>
                    </Pressable>
                )}
            </View>
        );
    };
    return (
        <Modal
            isVisible={visible}
            animationIn="slideInDown"
            animationOut="slideOutUp"
            presentationStyle="overFullScreen"
            onBackdropPress={() => onToggleVisible && onToggleVisible()}
            statusBarTranslucent
            style={{ justifyContent: 'flex-start', margin: 0 }}
            deviceWidth={width}
            deviceHeight={height}
            hasBackdrop>
            <LinearGradient
                pointerEvents="box-none"
                style={[styles.modalContainer, isIos() && { paddingTop: insets.top }]}
                colors={['#43435F', '#493E5A']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 0 }}>
                <View style={[styles.row, styles.between]}>
                    <Pressable onPress={prevMonth}>
                        <Icon name={'chevron-back-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                    </Pressable>
                    <View>
                        <Text style={styles.day}>
                            {selectedDate ? selectedDate.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD')}
                        </Text>
                    </View>
                    <Pressable onPress={nextMonth}>
                        <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                    </Pressable>
                </View>
                <View style={styles.weekContainer}>
                    {weekDays.map((day, index) => (
                        <Text key={index} style={styles.weekText}>
                            {day}
                        </Text>
                    ))}
                </View>
                <View {...panResponder.panHandlers}>
                    <FlatList
                        data={daysArray}
                        contentContainerStyle={{ flexGrow: 1 }}
                        renderItem={({ item, index }) => renderDay(item, index)}
                        keyExtractor={(item, index) => index.toString()}
                        numColumns={7}
                        scrollEnabled={false}
                    />
                </View>
            </LinearGradient>
        </Modal>
    );
}
const dayWidth = (width - px2dp(48)) / 7; // 每列宽度
const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    center: {
        justifyContent: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    modalContainer: {
        padding: px2dp(24),
        backgroundColor: '#454461',
        borderColor: 'rgba(255, 255, 255, 0.12)',
    },
    day: {
        color: '#fff',
        fontSize: scale(30),
    },
    dayContainer: {
        width: dayWidth,
        height: dayWidth,
        justifyContent: 'center',
        alignItems: 'center',
    },
    dayBox: {
        width: dayWidth,
        height: dayWidth,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(12),
    },
    todayBox: {
        backgroundColor: '#007BFF',
    },
    dayText: {
        textAlign: 'center',
        color: '#A4A4A4',
        fontSize: scale(28),
    },
    todayText: {
        color: '#fff',
        fontWeight: 'bold',
    },
    weekContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginVertical: px2dp(32),
    },
    weekText: {
        width: dayWidth,
        textAlign: 'center',
        fontWeight: 'bold',
        fontSize: scale(26),
        color: '#A4A4A4',
    },
});
